package cn.dg.manager.warehouse.service.impl;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.util.StringUtils;

import cn.dg.manager.base.util.DateUtil;
import cn.dg.manager.common.entity.PageEntity;
import cn.dg.manager.user.address.dao.UserAddressDao;
import cn.dg.manager.user.address.entity.UserAddressInfoVO;
import cn.dg.manager.warehouse.dao.WarehouseDetailDao;
import cn.dg.manager.warehouse.dao.WarehouseInfoDao;
import cn.dg.manager.warehouse.entity.WarehouseDetailInfoVO;
import cn.dg.manager.warehouse.entity.WarehouseDetailResultBean;
import cn.dg.manager.warehouse.entity.WarehouseEditPageBean;
import cn.dg.manager.warehouse.entity.WarehouseInfoResultBean;
import cn.dg.manager.warehouse.entity.WarehouseInfoVO;
import cn.dg.manager.warehouse.entity.WarehousePageParam;
import cn.dg.manager.warehouse.service.WareHouseService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service("wareHouseService")
public class WareHouseServiceImpl implements WareHouseService {

	public static String[] WAREHOUSE_INFO_HEADER = {"入库名称","入库总金额","收货人","手机号","收货地址","入库时间"};
	public static String[] WAREHOUSE_DETAIL_HEADER = {"商品分类","商品名称","商品单价","购买商品数量","商品购买总价"};
	public static int WAREHOUSE_INFO_CELL_START_INDEX = 1;
	public static String UTF_8 = "UTF-8";
	
	@Autowired
	WarehouseInfoDao warehouseInfoDao;
	
	@Autowired
	WarehouseDetailDao warehouseDetailDao;
	
	@Autowired
	UserAddressDao userAddressDao;
	
	public PageEntity<WarehouseInfoResultBean> getWarehouseListPage(Map<String, Object> params) {
        PageEntity<WarehouseInfoResultBean> list = warehouseInfoDao.findWarehouseListPage(params);
        return list;
	}

	/**
	 * 获取编辑入库信息
	 * 
	 */
	public List<WarehouseDetailResultBean> getWarehouseDetailInfo(Map<String, Object> params) {
		return warehouseDetailDao.getWarehouseDetailInfo(params);
	}

	/**
	 * 获取编辑入库信息
	 */
	public WarehouseEditPageBean getEditWarehouseInfoData(String warehouseId) {
		WarehouseEditPageBean result = warehouseInfoDao.getWarehouseInfo(warehouseId);
		List<WarehouseDetailInfoVO> itemList = warehouseDetailDao.getWarehouseDetailEditInfo(warehouseId);
		result.setItem(itemList);
		return result;
	}

	/**
	 * 删除入库信息
	 * 
	 */
	@Transactional(rollbackFor=Exception.class)
	public long deleteWareHouseInfo(List<String> warehouseIDList) {
		long rslt = 0;
		rslt = warehouseDetailDao.delWarehouseDetailInfoByIDList(warehouseIDList);
		rslt += warehouseInfoDao.deleteWarehouseInfoByIds(warehouseIDList);
		return rslt;
	}

	/**
	 * 入库信息Excel文件导出
	 * 
	 */
	public void exportExcelFile(String warehouseId, HttpServletResponse response) {
		 response.setCharacterEncoding(UTF_8);  
	        response.setContentType("application/vnd.ms-excel;charset=UTF-8");  
	        response.setHeader("Pragma", "no-cache");  
	        response.setHeader("Cache-Control", "no-cache");  
	        response.setDateHeader("Expires", 0);  
	        
	        WarehouseEditPageBean warehouseInfo = warehouseInfoDao.getWarehouseInfo(warehouseId);
			Map<String, Object> params = new HashMap<String, Object>(1);
			params.put("warehouseId", warehouseId);
			List<WarehouseDetailResultBean> warehouseDetailInfo = warehouseDetailDao.getWarehouseDetailInfo(params);
			
			String fileName = warehouseInfo.getWarehouseName().concat("_") + DateUtil.getSdfTimes() + ".xlsx";
			try {
				fileName = new String(fileName.getBytes(UTF_8), "ISO_8859_1");
			} catch (UnsupportedEncodingException e1) {
				fileName = DateUtil.getSdfTimes() + ".xlsx";
			}

			response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);  
			
			XSSFWorkbook workbook = new XSSFWorkbook();
			XSSFSheet sheet = workbook.createSheet(warehouseInfo.getWarehouseName());
			
			int createExcelRowCnt = 0;
			XSSFCellStyle  cellStyle = workbook.createCellStyle();
			cellStyle.setBorderLeft(BorderStyle.THIN);
			cellStyle.setBorderBottom(BorderStyle.THIN);
	        cellStyle.setBorderRight(BorderStyle.THIN);
	        cellStyle.setBorderTop(BorderStyle.THIN);

			XSSFCell cellHeader  = null;
			XSSFRow row  = null;
			
			int i = 0;
			// 入库名称
			row  = sheet.createRow(createExcelRowCnt);
			cellHeader = row.createCell(WAREHOUSE_INFO_CELL_START_INDEX);
			cellHeader.setCellValue(WAREHOUSE_INFO_HEADER[i]);
			cellHeader.setCellStyle(cellStyle);
			cellHeader = row.createCell(WAREHOUSE_INFO_CELL_START_INDEX + 1);
			cellHeader.setCellValue(warehouseInfo.getWarehouseName());
			cellHeader.setCellStyle(cellStyle);
			i++;
			createExcelRowCnt++;
			
			// 入库总金额
			row  = sheet.createRow(createExcelRowCnt);
			cellHeader = row.createCell(WAREHOUSE_INFO_CELL_START_INDEX);
			cellHeader.setCellValue(WAREHOUSE_INFO_HEADER[i]);
			cellHeader.setCellStyle(cellStyle);
			cellHeader = row.createCell(WAREHOUSE_INFO_CELL_START_INDEX + 1);
			cellHeader.setCellValue(warehouseInfo.getTotalPrice());
			cellHeader.setCellStyle(cellStyle);
			i++;
			createExcelRowCnt++;
			
			// 收货人
			row  = sheet.createRow(createExcelRowCnt);
			cellHeader = row.createCell(WAREHOUSE_INFO_CELL_START_INDEX);
			cellHeader.setCellValue(WAREHOUSE_INFO_HEADER[i]);
			cellHeader.setCellStyle(cellStyle);
			cellHeader = row.createCell(WAREHOUSE_INFO_CELL_START_INDEX + 1);
			cellHeader.setCellValue(warehouseInfo.getUserName());
			cellHeader.setCellStyle(cellStyle);
			i++;
			createExcelRowCnt++;
			
			// 手机号
			row  = sheet.createRow(createExcelRowCnt);
			cellHeader = row.createCell(WAREHOUSE_INFO_CELL_START_INDEX);
			cellHeader.setCellValue(WAREHOUSE_INFO_HEADER[i]);
			cellHeader.setCellStyle(cellStyle);
			cellHeader = row.createCell(WAREHOUSE_INFO_CELL_START_INDEX + 1);
			cellHeader.setCellValue(warehouseInfo.getTelPhone());
			cellHeader.setCellStyle(cellStyle);
			i++;
			createExcelRowCnt++;
			
			// 收货地址
			row  = sheet.createRow(createExcelRowCnt);
			cellHeader = row.createCell(WAREHOUSE_INFO_CELL_START_INDEX);
			cellHeader.setCellValue(WAREHOUSE_INFO_HEADER[i]);
			cellHeader.setCellStyle(cellStyle);
			cellHeader = row.createCell(WAREHOUSE_INFO_CELL_START_INDEX + 1);
			cellHeader.setCellValue(warehouseInfo.getAddress());
			cellHeader.setCellStyle(cellStyle);
			i++;
			createExcelRowCnt++;
			
			// 订单状态
			row  = sheet.createRow(createExcelRowCnt);
			cellHeader = row.createCell(WAREHOUSE_INFO_CELL_START_INDEX);
			cellHeader.setCellValue(WAREHOUSE_INFO_HEADER[i]);
			cellHeader.setCellStyle(cellStyle);
			cellHeader = row.createCell(WAREHOUSE_INFO_CELL_START_INDEX + 1);
			cellHeader.setCellValue(warehouseInfo.getUpdateTime());
			cellHeader.setCellStyle(cellStyle);
			i++;
			createExcelRowCnt++;
			
			row  = sheet.createRow(++createExcelRowCnt);
			for (int j = 0; j < WAREHOUSE_DETAIL_HEADER.length; j++) {
				cellHeader = row.createCell(j + WAREHOUSE_INFO_CELL_START_INDEX + 2);
				cellHeader.setCellValue(WAREHOUSE_DETAIL_HEADER[j]);
				cellHeader.setCellStyle(cellStyle);
			}
			createExcelRowCnt++;
			
			for (WarehouseDetailResultBean bean : warehouseDetailInfo) {
				int orderDetailCellIndex = WAREHOUSE_INFO_CELL_START_INDEX + 2;
				row  = sheet.createRow(createExcelRowCnt++);
				
				// 商品分类
				cellHeader = row.createCell(orderDetailCellIndex);
				cellHeader.setCellValue(bean.getTypeName());
				cellHeader.setCellStyle(cellStyle);
				orderDetailCellIndex++;
				
				// 商品名称
				cellHeader = row.createCell(orderDetailCellIndex);
				cellHeader.setCellValue(bean.getGoodName());
				cellHeader.setCellStyle(cellStyle);
				orderDetailCellIndex++;
				
				// 商品单价
				cellHeader = row.createCell(orderDetailCellIndex);
				cellHeader.setCellValue(bean.getPrice());
				cellHeader.setCellStyle(cellStyle);
				orderDetailCellIndex++;
				
				// 购买商品数量
				cellHeader = row.createCell(orderDetailCellIndex);
				cellHeader.setCellValue(bean.getQuantity());
				cellHeader.setCellStyle(cellStyle);
				orderDetailCellIndex++;
				
				// 商品购买总价
				cellHeader = row.createCell(orderDetailCellIndex);
				cellHeader.setCellValue(bean.getTotalPrice());
				cellHeader.setCellStyle(cellStyle);
				orderDetailCellIndex++;
			}
			
			OutputStream output = null;
			BufferedOutputStream bufferedOutPut = null;
			try {
				output = response.getOutputStream();
				bufferedOutPut = new BufferedOutputStream(output);
				bufferedOutPut.flush();
				workbook.write(bufferedOutPut);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				IOUtils.closeQuietly(bufferedOutPut);
				IOUtils.closeQuietly(output);
				IOUtils.closeQuietly(workbook);
			}
	}

	/**
	 * 生成入库信息
	 */
	@Transactional(rollbackFor=Exception.class)
	public long insertWarehouseInfo(WarehousePageParam bean) {
		WarehouseInfoVO warehouseInfoVO = getWarehouseInfoCopyValue(bean);
		warehouseInfoDao.insertWarehouseInfo(warehouseInfoVO);
		int orderDetailCnt = insertWarehouseDetailInfo(warehouseInfoVO.getWarehouseId(), bean.getWarehouseDetailJsonObject());
		return orderDetailCnt;
	}

	/**
	 * 
	 * @param warehouseId
	 * @param warehouseDetailJsonObject
	 * @return
	 */
	private int insertWarehouseDetailInfo(Integer warehouseId, Object warehouseDetailJsonObject) {
		int insertCnt = 0;
		JSONArray warehouseDetailJson = JSONArray.fromObject(warehouseDetailJsonObject);
		if(warehouseDetailJson != null && warehouseDetailJson.size() > 0) {
			List<WarehouseDetailInfoVO> orderDetailVOList = new ArrayList<WarehouseDetailInfoVO>(warehouseDetailJson.size());
			for (int i = 0; i < warehouseDetailJson.size(); i++) {
				WarehouseDetailInfoVO warehouseDetailVO = (WarehouseDetailInfoVO)JSONObject.toBean(
						warehouseDetailJson.getJSONObject(i), WarehouseDetailInfoVO.class);
				warehouseDetailVO.setWarehouseId(warehouseId);
				warehouseDetailVO.setSort(i + 1);
				orderDetailVOList.add(warehouseDetailVO);
			}
			insertCnt = warehouseDetailDao.insertWarehouseDetailList(orderDetailVOList);
		}
		return insertCnt;
	}

	/**
	 * 更新入库数据
	 */
	@Transactional(rollbackFor=Exception.class)
	public long updateWareHouseInfo(WarehousePageParam bean) {
		WarehouseInfoVO warehouseInfoVO = getWarehouseInfoCopyValue(bean);
		warehouseInfoDao.updateWarehouseInfo(warehouseInfoVO);
		int updateDetailCnt = updateWarehouseDetailInfo(warehouseInfoVO.getWarehouseId(), bean.getWarehouseDetailJsonObject());
		return updateDetailCnt;
	}

	/**
	 * 更新入库详细
	 * 
	 * @param warehouseId
	 * @param warehouseDetailJsonObject
	 * @return
	 */
	private int updateWarehouseDetailInfo(Integer warehouseId, Object warehouseDetailJsonObject) {
		int rslt = 0;
		// 删除全部订单详情
		rslt += warehouseDetailDao.delWarehouseDetailInfoByIDList(Arrays.asList(warehouseId.toString()));
		// 全新插入
		rslt += insertWarehouseDetailInfo(warehouseId, warehouseDetailJsonObject);
		return rslt;
	}

	/**
	 * 准备入库基本信息
	 * @param bean
	 * @return
	 */
	private WarehouseInfoVO getWarehouseInfoCopyValue(WarehousePageParam bean) {
		// 地址ID设定
		bean.setAddressId(saveAddressInfo(bean));
		WarehouseInfoVO warehouseInfoVO = new WarehouseInfoVO();
		warehouseInfoVO.setWarehouseId(bean.getWarehouseId());
		warehouseInfoVO.setWarehouseName(bean.getWarehouseName());
		warehouseInfoVO.setAddressId(bean.getAddressId());
		warehouseInfoVO.setTotalCnt(bean.getTotalCnt());
		warehouseInfoVO.setTotalPrice(bean.getTotalPrice());
		warehouseInfoVO.setTotalPriceJp(bean.getTotalPriceJp());
		warehouseInfoVO.setDelFlg(0);
		return warehouseInfoVO;
	}
	
	/**
	 * 收货地址设定
	 * @param bean
	 * @return
	 */
	private Integer saveAddressInfo(WarehousePageParam bean) {
		Integer addressId = 0;
		if (StringUtils.isEmpty(bean.getUserName())) {
			return addressId;
		}
		
		UserAddressInfoVO addressVO = new UserAddressInfoVO();
		addressVO.setUserName(bean.getUserName());
		addressVO.setPostCode(bean.getPostCode());
		addressVO.setTelPhone(bean.getTelPhone());
		addressVO.setAddress(bean.getAddress());
		// 新增
		if(bean.getAddressId() == null || bean.getAddressId() == 0) {
			long rslt = userAddressDao.insertUserAddressInfo(addressVO);
			if (rslt > 0) {
				addressId = addressVO.getAddressId();
			}
		} else {
			Map<String, Object> conds = new HashMap<String, Object>();
			conds.put("userName", bean.getUserName());
			conds.put("postCode", bean.getPostCode());
			conds.put("telPhone", bean.getTelPhone());
			conds.put("address", bean.getAddress());
			long rslt = userAddressDao.findUserAddressByCond(conds);
			if (rslt <= 0 ) {
				long insertRslt = userAddressDao.insertUserAddressInfo(addressVO);
				if (insertRslt > 0) {
					addressId = addressVO.getAddressId();
				}
			} else {
				addressId = bean.getAddressId();
			}
		}
		return addressId;
	}

}
